import axios from 'axios';

import type { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';

//封装axios

const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 100000,
});

instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 获取token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = 'Bearer ' + token;
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);

instance.interceptors.response.use(
  (response: any) => {
    const { status, message } = response.data;

    if (status == 200) {
      return response.data;
    } else if (status == 1000) {
      console.log('not logged on');
    } else {
      message.error(message);
    }
    return Promise.reject(new Error(message)); //失败的promise
  },
  (error: AxiosError) => {
    let message = '';
    const Status = error.response?.status;
    if (Status) {
      switch (Status) {
        case 401:
          message = 'Token expiration';
          break;
        case 403:
          message = 'Unauthorized access';
          break;
        case 404:
          message = 'Request address error';
          break;
        case 500:
          message = 'There is a problem with the server';
          break;
        default:
          message = 'Other errors';
      }
    }
    console.log(message);

    return Promise.reject(error);
  },
);

export default instance;
